## 这个是监测到画面有明显变化拍照识别，10s无明显变化则不拍照。正在修改
from ultralytics import YOLO
import cv2
import time
import os
from PIL import Image

# 创建输出文件夹
output_folder = 'imgsOut'
input_folder = 'imgsIn'
os.makedirs(output_folder, exist_ok=True)
os.makedirs(input_folder, exist_ok=True)

# 加载预训练的YOLOv8n模型
model = YOLO('results_runs/dataSet_good2/E10_IZ64/classify/train/weights/best.pt')

# 从摄像头捕捉图像
cap = cv2.VideoCapture(0)  # 0表示默认摄像头

# 初始化变量
prev_frame = None
motion_detected = False

while True:
    ret, frame = cap.read()  # 读取图像帧
    if not ret:
        break

    # 如果未检测到运动，则休眠待机
    if not motion_detected:
        # 对比当前帧与上一帧
        if prev_frame is not None and cv2.absdiff(prev_frame, frame).mean() < 1:
            time.sleep(10)
            continue

    # 更新上一帧
    prev_frame = frame.copy()

    # 在图像上运行推理
    results = model(frame)

    # 获取当前时间戳
    timestamp = int(time.time())

    # 保存图像到输入文件夹
    input_image_path = os.path.join(input_folder, f'{timestamp}.jpg')
    cv2.imwrite(input_image_path, frame)

    # 处理识别结果
    for i, r in enumerate(results):
        im_array = r.plot()  # 绘制包含预测结果的BGR numpy数组
        im = Image.fromarray(im_array[..., ::-1])  # RGB PIL图像
        output_image_path = os.path.join(output_folder, f'{timestamp}_{i}.jpg')
        im.save(output_image_path)  # 保存识别结果图像

    # 检测画面是否有明显变化
    motion_detected = cv2.absdiff(prev_frame, frame).mean() > 300


    

cap.release()  # 释放摄像头
cv2.destroyAllWindows()  # 关闭所有窗口
